<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="商户类型" prop="merchant_type">
            <el-select v-model="form.merchant_type" placeholder="请选择商户类型">
              <el-option v-for="item in merchantTypeList" :key="item.id" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业执照名称：" prop="company_name">
            <el-input v-model.trim="form.company_name" placeholder="营业执照名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="11">
          <el-form-item label="商户简称：" prop="alias_name">
            <el-input v-model.trim="form.alias_name" placeholder="商户简称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-tooltip placement="top" content="支付宝账单中的商户名称会展示此处设置的别名，如果涉及支付宝APP内的支付，支付结果页也会展示该别名。如果涉及当面付场景，请填写线下店铺名称">
            <el-icon class="icon-wzg-config"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码：" prop="business_licence_number">
            <el-input v-model.trim="form.business_licence_number" placeholder="统一社会信用代码"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="营业执照：" prop="business_licence_cert">
            <UploadImageInfo :imageWidth="178" :imageHeight="178" :limit="800" :acceptList="['.jpg', '.jpeg', '.png']" suggestInfo="只支持.jpg .png格式" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="business_licence_cert" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">法人信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="身份证号：" prop="legal_person_id_number">
            <el-input v-model.trim="form.legal_person_id_number" placeholder="身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法定代表人/负责人：" prop="legal_person">
            <el-input v-model.trim="form.legal_person" placeholder="法定代表人/负责人"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">经营信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="联系人：" prop="name">
            <el-input v-model.trim="form.name" placeholder="联系人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model.trim="form.mobile" placeholder="手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <!-- <el-col :span="12">
          <el-form-item label="联系人邮箱："
                        prop="name">
            <el-input v-model.trim="form.name"
                      placeholder="联系人邮箱"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="签约支付宝号：" prop="enterprise_alipay_account">
            <el-input v-model.trim="form.enterprise_alipay_account" placeholder="签约支付宝号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">其他信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="投资金额：" prop="actual_investment_amount">
            <el-input v-model.trim="form.actual_investment_amount" :disabled="methodType == 'PUT'" placeholder="投资金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业支付宝余额：" prop="enterprise_alipay_account_balance">
            <el-input v-model.trim="form.enterprise_alipay_account_balance" :disabled="methodType == 'PUT'" placeholder="企业支付宝余额"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="审核结果" prop="status">
            <el-select v-model="form.status" placeholder="请选择审核结果">
              <el-option v-for="item in statusList" :key="item.id" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入审核备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="预计投资金额：" prop="expect_investment_amount">
            <el-input v-model.trim="form.expect_investment_amount" :disabled="methodType == 'PUT'" placeholder="预计投资金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计投资时间：" prop="expect_investment_time">
            <el-date-picker v-model="form.expect_investment_time" type="date" format="YYYY/MM/DD" value-format="x" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="合同：" prop="contract_url">
            <UploadResourcesInfo v-model:disabledbtn="disabledbtn" v-model:loading="loading" resourceKey="contract_url" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin: 0 70px">
        <el-descriptions :column="2" size="default">
          <el-descriptions-item label="申请时间">{{ handleVerifyFormatDate(Number(form.create_time)) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import UploadResourcesInfo from "@/components/common/UploadResourcesInfo.vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IInvestorsInfoDTO, IInvestorsInfoVo } from "@/types/user/investorsInfo";
import { commonInvestorsInfo, getInvestorsByIdInfo } from "@/utils/api/admin/merchant/investors";
import { useDictData } from "@/hooks/network/useDictData";
import type { IDictData } from "@/types/dict";
import { timeVerify } from "@/utils/utils";
import type { InternalRuleItem } from "async-validator";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
  statusList: Array<IDictData>;
}
const { id, statusList } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
  handleViewContractInfo: [url: string];
}>();
let { getDictData } = useDictData();
/* 商户类型 */
const merchantTypeList = ref<Array<IDictData>>([]);
const isDisabledbtn = ref(false);
const checkAll = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IInvestorsInfoDTO>({
  id: 0,
  name: "",
  status: "",
  mobile: "",
  expect_investment_amount: "",
  expect_investment_time: 0,
  actual_investment_amount: "",
  legal_person: "",
  legal_person_id_number: "",
  business_licence_cert: "",
  business_licence_number: "",
  company_name: "",
  enterprise_alipay_account: "",
  enterprise_alipay_account_balance: "",
  alias_name: "",
  contract_url: "",
  create_time: "",
  merchant_type: "",
  pass_time: 0,
  remark: ""
});
const rules = reactive({
  merchant_type: [{ required: true, message: "请选择商户类型", trigger: "blur" }],
  mobile: [{ required: true, message: "请填写手机号", trigger: "blur" }],
  name: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  company_name: [{ required: true, message: "请填写营业执照名称", trigger: "blur" }],
  alias_name: [{ required: true, message: "请填写商户简称", trigger: "blur" }],
  business_licence_number: [{ required: true, message: "请填写统一社会信用代码", trigger: "blur" }],
  enterprise_alipay_account: [{ required: true, message: "请填写企业支付宝账号", trigger: "blur" }],
  enterprise_alipay_account_balance: [{ required: true, message: "请填写支付宝余额", trigger: "blur" }],
  actual_investment_amount: [{ required: true, message: "请填写投资金额", trigger: "blur" }],
  legal_person_id_number: [{ required: true, message: "请填写身份证号", trigger: "blur" }],
  legal_person: [{ required: true, message: "请填写支付宝余额", trigger: "blur" }],
  business_licence_cert: [{ required: true, message: "请上传营业执照", trigger: "blur" }],
  expect_investment_time: [
    {
      required: true,
      validator: (rule: InternalRuleItem, value: string | number, callback: (error?: Error) => void) => {
        timeVerify(rule, value, callback, "请选择预计投资时间");
      },
      trigger: "blur"
    }
  ],
  status: [{ required: true, message: "请选择审核状态", trigger: "blur" }]
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetMallRedPacketPurchaseByIdInfo(id);
    }
  }
);

/* 获取活动详情信息 */
function handleGetMallRedPacketPurchaseByIdInfo(id: number) {
  toggleState(true);
  getInvestorsByIdInfo<IInvestorsInfoVo, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.name = res.result.name;
      form.mobile = res.result.mobile;
      form.status = res.result.status;
      form.expect_investment_amount = res.result.expect_investment_amount;
      form.expect_investment_time = res.result.expect_investment_time * 1000;
      form.actual_investment_amount = res.result.actual_investment_amount;

      form.legal_person = res.result.legal_person;
      form.legal_person_id_number = res.result.legal_person_id_number;
      form.business_licence_cert = res.result.business_licence_cert;
      form.business_licence_number = res.result.business_licence_number;
      form.company_name = res.result.company_name;
      form.enterprise_alipay_account = res.result.enterprise_alipay_account;
      form.enterprise_alipay_account_balance = res.result.enterprise_alipay_account_balance;
      form.alias_name = res.result.alias_name;
      form.contract_url = res.result.contract_url;
      form.remark = res.result.remark;
      form.merchant_type = res.result.merchant_type;
      form.create_time = res.result.create_time + "";
      form.pass_time = res.result.pass_time;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  checkAll.value = false;

  form.id = 0;
  form.create_time = "";
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存校验数据 */
function handleValidate() {
  return true;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleValidate()) return;
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonInvestorsInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

getDictData("ZFT_INVESTOR_MERCHANT_TYPE", merchantTypeList);
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
